package lzh.com.customeroilactivity.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import lzh.com.customeroilactivity.BaseActivity;
import lzh.com.customeroilactivity.Bean.BespeakRefual;
import lzh.com.customeroilactivity.R;
import lzh.com.customeroilactivity.util.TImeTickerUtils;

public class RefuelActivity extends BaseActivity {

    private String name;
    private String iphone;
    private String address;
    private String detailAddress;

    private TextView tvReceiveAddress;
    private TextView receiveAddress;
    private TextView companyName;
    private TextView time;
    private TextView oilType;
    private TextView money;
    private TextView quantity;
    private TextView mode;
    private TextView equipment;
    private EditText remarks;
    private Button go;

    private int oilTypeId = 0;
    private int button1Id = 0;
    private int button2Id = 1;
    private String string;
    private int modeId = 0;
    private int eNumber1 = 0;
    private int eNumber2 = 0;
    private int eNumber3 = 0;

    private SharedPreferences sharedPreferences;
    private int dataNumber = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refuel);
        sharedPreferences = this.getSharedPreferences("userData",MODE_PRIVATE);
        showDialog();
        init();
    }

    private void init(){
        RelativeLayout layout1 = (RelativeLayout)findViewById(R.id.layout1);
        RelativeLayout layout2 = (RelativeLayout)findViewById(R.id.layout2);
        RelativeLayout layout3 = (RelativeLayout)findViewById(R.id.layout3);
        time = (TextView)findViewById(R.id.time);
        ImageButton back = (ImageButton)findViewById(R.id.top_left_btn);
        tvReceiveAddress = (TextView)findViewById(R.id.tv_receive_address);
        receiveAddress = (TextView)findViewById(R.id.receive_address);
        companyName = (TextView)findViewById(R.id.company_name);
        oilType = (TextView)findViewById(R.id.oil_type);
        money = (TextView)findViewById(R.id.money);
        quantity = (TextView)findViewById(R.id.quantity);
        mode = (TextView)findViewById(R.id.mode);
        equipment = (TextView)findViewById(R.id.equipment);
        remarks = (EditText)findViewById(R.id.remarks);
        go = (Button)findViewById(R.id.go);

        layout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RefuelActivity.this,ReceivingAddressActivity.class);
                startActivityForResult(intent,0);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        layout2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TImeTickerUtils.getInstance().initTheDatePickers(RefuelActivity.this, time);

            }
        });

        layout3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RefuelActivity.this,CompanyActivity.class);
                startActivityForResult(intent,1);
            }
        });

        oilType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                oilClick();
            }
        });

        quantity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (money.getText().toString().length() == 0){
                    Toast.makeText(RefuelActivity.this, "请选择油品类型", Toast.LENGTH_SHORT).show();
                }else {
                    quantityClick();
                }
            }
        });

        mode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                modeClick();
            }
        });

        equipment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                equipmentClick();
            }
        });

        go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                find();
            }
        });
    }

    private void showDialog(){
        View view = LayoutInflater.from(RefuelActivity.this).inflate(R.layout.refuel_dialog,null);
        TextView content = (TextView)view.findViewById(R.id.content);
        TextView sure = (TextView)view.findViewById(R.id.sure);

        final AlertDialog dialog = new AlertDialog.Builder(RefuelActivity.this,R.style.DialogStyle)
                .setView(view)
                .create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        content.setText("如果您需要开具公司发票，开票公司必须如本页面中选择的交易公司名相同。下单页面中不选择交易公司信息，则无法开具公司发票");
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });


    }

    private void oilClick(){
        View view = LayoutInflater.from(this).inflate(R.layout.oil_type_dialog,null);
        RadioButton content = (RadioButton)view.findViewById(R.id.content);
        TextView no = (TextView)view.findViewById(R.id.no);
        TextView yes = (TextView)view.findViewById(R.id.yes);
        if (oilTypeId == 1){
            content.setChecked(true);
        }
        AlertDialog dialog = new AlertDialog.Builder(this,R.style.DialogStyle)
                .setView(view)
                .create();
        dialog.show();

        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (content.isChecked()){
                    oilTypeId = 1;
                    oilType.setText("柴油 国V0#");
                    money.setText("6.98元");
                    dialog.dismiss();
                }else {
                    Toast.makeText(RefuelActivity.this, "请选择油品类型", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void quantityClick(){
        View view = LayoutInflater.from(this).inflate(R.layout.quantity_dialog,null);
        EditText editText = (EditText)view.findViewById(R.id.edit);
        TextView result = (TextView)view.findViewById(R.id.result);
        RadioButton radioButton1 = (RadioButton)view.findViewById(R.id.button1);
        RadioButton radioButton2 = (RadioButton)view.findViewById(R.id.button2);
        TextView no = (TextView)view.findViewById(R.id.no);
        TextView yes = (TextView)view.findViewById(R.id.yes);

        AlertDialog dialog = new AlertDialog.Builder(this,R.style.DialogStyle)
                .setView(view)
                .create();
        dialog.show();

        editText.setText(string);
        editText.setSelection(editText.length());
        if (button1Id == 0 && button2Id ==1){
            radioButton1.setChecked(false);
            radioButton2.setChecked(true);

            string = editText.getText().toString();
            if (string.equals("")){
                string = "0";
            }
            try {
                int anInt = Integer.parseInt(string);
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                String num = df.format((float)anInt*6.98);//返回的是String类型
                result.setText(num+"元");
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

        }else {
            radioButton1.setChecked(true);
            radioButton2.setChecked(false);

            string = editText.getText().toString();
            if (string.equals("")){
                string = "0";
            }

            try {
                int anInt = Integer.parseInt(string);
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                String num = df.format((float)anInt/6.98);//返回的是String类型
                result.setText(num+"升");
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

        }
        radioButton1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    button1Id = 1;
                    button2Id = 0;
                    string = editText.getText().toString();
                    if (string.equals("")){
                        string = "0";
                    }

                    try {
                        int anInt = Integer.parseInt(string);
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        String num = df.format((float)anInt/6.98);//返回的是String类型
                        result.setText(num+"升");
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                }else {
                    button1Id = 0;
                    button2Id = 1;
                    string = editText.getText().toString();
                    if (string.equals("")){
                        string = "0";
                    }
                    try {
                        int anInt = Integer.parseInt(string);
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        String num = df.format((float)anInt*6.98);//返回的是String类型
                        result.setText(num+"元");
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                string = charSequence.toString();
                if (string.equals("")){
                    string = "0";
                }

                if (button1Id == 0 && button2Id == 1){
                    try {
                        int anInt = Integer.parseInt(string);
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        String num = df.format((float)anInt*6.98);//返回的是String类型
                        result.setText(num+"元");
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }else if (button1Id == 1 && button2Id == 0){
                    try {
                        int anInt = Integer.parseInt(string);
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        String num = df.format((float)anInt/6.98);//返回的是String类型
                        result.setText(num+"升");
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = result.getText().toString();
                boolean status = s.contains("元");
                boolean newStatus = s.contains("升");
                if(null == string | string.equals("")){
                    string = "0";
                }
                if (status){
                    quantity.setText(string+"升"+"("+result.getText()+")");
                }
                if (newStatus){
                    quantity.setText(string+"元"+"("+result.getText()+")");
                }
                dialog.dismiss();
            }
        });
    }

    private void modeClick(){
        View view = LayoutInflater.from(this).inflate(R.layout.mode_dialog,null);
        RadioButton button1 = (RadioButton)view.findViewById(R.id.button1);
        RadioButton button2 = (RadioButton)view.findViewById(R.id.button2);
        RadioButton button3 = (RadioButton)view.findViewById(R.id.button3);
        TextView no = (TextView)view.findViewById(R.id.no);
        TextView yes = (TextView)view.findViewById(R.id.yes);

        if (modeId == 1){
            button1.setChecked(true);
        }else if (modeId == 2){
            button2.setChecked(true);
        }else if (modeId == 3){
            button3.setChecked(true);
        }

        AlertDialog dialog = new AlertDialog.Builder(this,R.style.DialogStyle)
                .setView(view)
                .create();
        dialog.show();

        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (button1.isChecked()){
                    modeId = 1;
                    mode.setText("灌桶");
                    dialog.dismiss();
                }else if (button2.isChecked()){
                    modeId = 2;
                    mode.setText("换桶");
                    dialog.dismiss();
                }else if (button3.isChecked()){
                    modeId = 3;
                    mode.setText("车对车");
                    dialog.dismiss();
                }else {
                    Toast.makeText(RefuelActivity.this, "请选择加注方式", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void equipmentClick(){
        View view = LayoutInflater.from(this).inflate(R.layout.equipment_dialog,null);
        ImageButton tv1Reduce = (ImageButton)view.findViewById(R.id.tv1_reduce);
        TextView number1 = (TextView)view.findViewById(R.id.number1);
        ImageButton tv1plus = (ImageButton)view.findViewById(R.id.tv1_plus);
        ImageButton tv2Reduce = (ImageButton)view.findViewById(R.id.tv2_reduce);
        TextView number2 = (TextView)view.findViewById(R.id.number2);
        ImageButton tv2plus = (ImageButton)view.findViewById(R.id.tv2_plus);
        ImageButton tv3Reduce = (ImageButton)view.findViewById(R.id.tv3_reduce);
        TextView number3 = (TextView)view.findViewById(R.id.number3);
        ImageButton tv3plus = (ImageButton)view.findViewById(R.id.tv3_plus);
        TextView no = (TextView)view.findViewById(R.id.no);
        TextView yes = (TextView)view.findViewById(R.id.yes);

        number1.setText(eNumber1+"");
        number2.setText(eNumber2+"");
        number3.setText(eNumber3+"");

        AlertDialog dialog = new AlertDialog.Builder(this,R.style.DialogStyle)
                .setView(view)
                .create();
        dialog.show();

        tv1plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                eNumber1++;
                number1.setText(eNumber1+"");
            }
        });

        tv1Reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (eNumber1 > 0){
                    eNumber1--;
                    number1.setText(eNumber1+"");
                }
            }
        });

        tv2plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                eNumber2++;
                number2.setText(eNumber2+"");
            }
        });

        tv2Reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (eNumber2 > 0){
                    eNumber2--;
                    number2.setText(eNumber2+"");
                }
            }
        });

        tv3plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                eNumber3++;
                number3.setText(eNumber3+"");
            }
        });

        tv3Reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (eNumber3 > 0){
                    eNumber3--;
                    number3.setText(eNumber3+"");
                }
            }
        });

        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                equipment.setText("油桶x"+eNumber1+"，塑料吨桶x"+eNumber2+"，手摇泵x"+eNumber3);
                dialog.dismiss();
            }
        });

    }

    private void find(){
        BmobQuery<BespeakRefual> bmobQuery = new BmobQuery<BespeakRefual>();
        bmobQuery.addWhereEqualTo("userId",sharedPreferences.getInt("userId",0));
        bmobQuery.findObjects(new FindListener<BespeakRefual>() {
            @Override
            public void done(List<BespeakRefual> list, BmobException e) {
                if (e == null){

                    long clickTime = System.currentTimeMillis();

                    BespeakRefual add = new BespeakRefual();
                    add.setUserId(sharedPreferences.getInt("userId",0));
                    add.setBespeakRefualId(clickTime+""+sharedPreferences.getInt("userId",0)+"");
                    add.setName(name);
                    add.setIphone(iphone);
                    add.setCompanyAddress(address+detailAddress);
                    add.setState("待服务");
                    add.setTime(time.getText().toString());
                    add.setCompanyName(companyName.getText().toString());
                    add.setOilType(oilType.getText().toString());
                    add.setMoney(money.getText().toString());
                    add.setQuantity(quantity.getText().toString());
                    add.setMode(mode.getText().toString());
                    add.setEquipment(equipment.getText().toString());
                    add.setRemarks(remarks.getText().toString());
                    add.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null){
                                finish();
                                Toast.makeText(RefuelActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(RefuelActivity.this, "保存失败，请联系管理员，qq:389617853", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                }
            }
        });
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 0:
                try {
                    Bundle bundle = data.getExtras();
                    name = bundle.getString("name");
                    iphone = bundle.getString("iphone");
                    address = bundle.getString("address");
                    detailAddress = bundle.getString("detailAddress");

                    tvReceiveAddress.setVisibility(View.VISIBLE);
                    receiveAddress.setText(name+iphone+"\n"+address+detailAddress);

                }catch (NullPointerException e){
                    e.printStackTrace();
                }
               break;
            case 1:
                try{
                    Bundle bundle = data.getExtras();
                    name = bundle.getString("name");
                    companyName.setText(name);
                }catch (NullPointerException e){
                    e.printStackTrace();
                }
            default:
                break;
        }
    }
}
